<template>
  <el-badge
    class="bounceIn"
    :value="dataInfo.totalCount"
    :type="dataInfo.type"
    :show-zero="false"
  >
    <div
      :class="[
        'card-wrapper',
        'flow-card',
        dataInfo.totalCount == 0 ? 'flow-card-collapsed' : '',
      ]"
      @contextmenu.prevent="handleRightClick(true)"
      @mousemove="handleHover(true)"
      @mouseout="handleHover(false)"
    >
      <!-- Content -->
      <div class="widget-header">
        <el-button type="info" size="large" link>
          <b>流量状态</b>
          <span style="margin-left: 6px; margin-top: 2px">
            <el-icon
              v-if="dataInfo.totalCount == 0"
              style="color: var(--el-color-success)"
            >
              <SuccessFilled />
            </el-icon>
            <!-- <el-icon
              v-else-if="dataInfo.dangerCount > 0"
              style="color: var(--el-color-error)"
            >
              <CircleCloseFilled />
            </el-icon>
            <el-icon
              v-else-if="dataInfo.warningCount > 0"
              style="color: var(--el-color-warning)"
            >
              <WarningFilled />
            </el-icon> -->
          </span>
        </el-button>
        <el-button
          type="info"
          size="large"
          link
          @click="flowLimitsSetter.open()"
          @dbclick="
            flowStore.widgetContent.showRawViewer =
              !flowStore.widgetContent.showRawViewer
          "
          @contextmenu.prevent="
            flowStore.widgetContent.showRawViewer =
              !flowStore.widgetContent.showRawViewer
          "
        >
          <el-icon><Tools /></el-icon>
        </el-button>
      </div>
      <div class="widget-body" v-if="dataInfo.totalCount > 0">
        <el-scrollbar height="100%">
          <div
            style="padding: 4px 6px"
            @click="
              flowStore.widgetContent.showDataViewer =
                !flowStore.widgetContent.showDataViewer
            "
          >
            <!-- <div
              v-if="dataInfo.totalCount == 0"
              style="
                color: var(--el-color-success);
                display: flex;
                flex-direction: column;
                justify-content: center;
                align-items: center;
              "
            >
              <div style="font-size: 48px">
                <el-icon><SuccessFilled /></el-icon>
              </div>
              <div style="padding-top: 12px">流量正常</div>
            </div> -->
            <div
              v-for="c in resultFiltered"
              :style="{
                color:
                  c.type == 'danger'
                    ? 'var(--el-color-danger)'
                    : c.type == 'warning'
                    ? 'var(--el-color-warning)'
                    : 'var(--el-color-info)',
              }"
              class="content-line"
            >
              <div class="content-line-icon">
                <el-icon v-if="c.type == 'danger'"
                  ><CircleCloseFilled
                /></el-icon>
                <el-icon v-else-if="c.type == 'warning'"
                  ><WarningFilled
                /></el-icon>
              </div>
              <div class="content-line-text">
                <div style="font-weight: bolder">
                  <span>{{ c.from.format("HH:mm") }}</span>
                  <span style="padding: 0 2px">至</span>
                  <span>{{ c.to.format("HH:mm") }}</span>
                </div>
                <div>
                  <span style="padding-right: 4px">{{ c.remark }} </span>
                  <span>{{ c.value }} </span>
                  <span style="padding: 0 2px" v-if="c.type == 'danger'"
                    >≥</span
                  >
                  <span style="padding: 0 2px" v-else-if="c.type == 'warning'"
                    >≈</span
                  >
                  <span>{{ c.limit }} </span>
                </div>
              </div>
            </div>
          </div>
        </el-scrollbar>
      </div>
      <!-- <div class="widget-footer" v-if="dataInfo.type != 'success'">
        <span>@{{ dataInfo.updatingTime }}</span>
        <span>{{ dataInfo.lastComsumption }}ms</span>
      </div> -->
      <RawDataViewer
        ref="rawDataViewer"
        :result="result"
        :dataInfo="dataInfo"
        :show="flowStore.widgetContent.showRawViewer"
        @close="flowStore.widgetContent.showRawViewer = false"
      />
      <DataViewer
        ref="rawDataViewer"
        :result="resultFiltered"
        :dataInfo="dataInfo"
        :show="flowStore.widgetContent.showDataViewer"
        @close="flowStore.widgetContent.showDataViewer = false"
      />
      <FlowLimitsSetter ref="flowLimitsSetter" @update="handleCompute()" />
    </div>
  </el-badge>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from "vue";
import dayjs from "dayjs";
import useFlowStore from "@/store/flow.js";
import { cumulate } from "../utils";
import checkFlwLimits from "./checkFlowLimits.js";

import RawDataViewer from "./RawDataViewer.vue";
import DataViewer from "./DataViewer.vue";
import FlowLimitsSetter from "./FlowLimitsSetter.vue";

const rawDataViewer = ref();
const flowLimitsSetter = ref();

const flowStore = useFlowStore();

const isHovering = ref(false);

const handleHover = (val) => {
  isHovering.value = val;
};

const result = ref([]);
const duration = ref(0);
const version = ref(0);

const showRawData = ref(false);

const resultFiltered = ref([]);

const dataInfo = ref({
  lastComsumption: 0,
  updatingTime: 0,
  totalCount: 0,
  type: "info",
  warningCount: 0,
  dangerCount: 0,
});

const step = ref(2);
const stepMinute = ref(30);
const rangeHour = ref(6);
const flowVersion = ref(0);
const handleCompute = () => {
  if (false) {
    // flowVersion.value == flowStore.version
    return false;
  } else {
    flowVersion.value = flowStore.version;
    let t0 = new Date().getTime();
    let flowValuesHalf = cumulate(flowStore.rawData, step.value, 2);
    let flowValuesFull = cumulate(flowStore.rawData, step.value, 4);
    // console.log("checkFlwLimits", flowValuesHalf, flowValuesFull);
    result.value = checkFlwLimits(
      flowStore.begTime,
      flowValuesHalf,
      flowValuesFull,
      flowStore.tags,
      flowStore.flowLimits,
      stepMinute.value,
      rangeHour.value
    );
    // filter result
    resultFiltered.value = result.value.filter(
      (cell) =>
        cell.to.isSameOrAfter(dayjs(), "hour") &&
        cell.from.diff(dayjs(), "hour") <= 12
    );
    // dataInfo
    let warningCount = resultFiltered.value.filter(
      (c) => c.type == "warning"
    ).length;
    let dangerCount = resultFiltered.value.filter(
      (c) => c.type == "danger"
    ).length;
    dataInfo.value = {
      lastComsumption: duration.value,
      updatingTime: dayjs(version.value).format("HH:mm:ss"),
      totalCount: resultFiltered.value.length,
      type: dangerCount > 0 ? "danger" : warningCount > 0 ? "warning" : "info",
      warningCount,
      dangerCount,
    };
    // set flow store
    flowStore.widgetContent.count = dataInfo.value.totalCount;
    flowStore.widgetContent.type = dataInfo.value.type;
    flowStore.widgetContent.result = result.value;
    flowStore.widgetContent.resultFiltered = resultFiltered.value;
    // set duration
    let t1 = new Date().getTime();
    duration.value = t1 - t0;
    version.value = t1;
    // console.log(
    //   "FlowWidget",
    //   "Moment: " + dayjs().format("HH:mm:ss"),
    //   "Duration: " + duration.value
    //   // "Content: ",
    //   // JSON.stringify(result.value, null, 2)
    // );
  }
};

const handleRightClick = (val) => (showRawData.value = true);

const timmer = ref();

onMounted(() => {
  handleCompute();
  if (!timmer.value) {
    timmer.value = setInterval(() => handleCompute(), 2000);
  }
});

onUnmounted(() => {
  if (timmer.value) {
    clearInterval(timmer.value);
  }
});
</script>

<style scoped>
@import "@/styles/card.css";
@import "@/styles/vibrate.css";
@import "@/styles/blinking.css";

.flow-card {
  font-size: 12px;
  text-shadow: 0 1px 4px rgba(0, 0, 0, 0.4);
  background-color: var(--theme-color-flow-card);
  overflow: hidden;
}

.flow-card-collapsed {
  height: 30px;
}

.widget-header {
  width: 100%;
  height: 26px;
  padding: 2px 8px 0 12px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  overflow: hidden;
}

.widget-body {
  width: 100%;
  height: 134px;
  overflow: hidden;
  border-top: 1px solid #8888;
  /* border-bottom: 1px solid #8888; */
}

.widget-footer {
  width: 100%;
  height: 22px;
  padding: 0 12px 1px 12px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  overflow: hidden;
  color: var(--el-color-info);
}

.content-line {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 2px 0;
}

.content-line-icon {
  font-size: 24px;
  padding-right: 6px;
  padding-top: 2px;
}
.content-line-text {
  width: 100%;
}
</style>
